package com.luke.boot.spring_security.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    //登录成功跳转的Controller
    @RequestMapping(value = "login-success", produces = {"text/plain;charset=UTF-8"})
    public String loginSuccess() {
        return getUsername() + "登录成功";
    }

    @PreAuthorize(value = "hasAuthority('p1')")//权限注解：资源（方法）和权限绑定
    @GetMapping(value = "/r/r1", produces = {"text/plain;charset=UTF-8"})
    public String r1() {
        return getUsername() + " 访问资源1";
    }

    @PreAuthorize(value = "hasAnyAuthority('p2')")//权限注解：资源（方法）和权限绑定
    @GetMapping(value = "/r/r2", produces = {"text/plain;charset=UTF-8"})
    public String r2() {
        return getUsername() + " 访问资源2";
    }

    @GetMapping(value = "/test", produces = {"text/plain;charset=UTF-8"})
    public String test() {
        return getUsername() + " 访问公开资源";
    }

    /**
     * 获取当前登录用户名
     *
     * @return
     */
    private String getUsername() {
        //获取到当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!authentication.isAuthenticated()) { //还没有认证（登录）
            return null;
        }
        Object principal = authentication.getPrincipal();
        String username = null;
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else {
            username = principal.toString();
        }
        return username;
    }

}
